﻿using System.Data.SqlClient;

namespace HenhouseEnvironmentCtrl
{
    public static class DBConnection
    {
        public static User User;

        public static SqlConnection CreateConnection()
        {
            string connectionString = "Data Source=MHCLL;Initial Catalog=HenhouseEnvironmentCtrl;Integrated Security=True;";
            return new SqlConnection(connectionString);
        }

        public static void Open(SqlConnection conn)
        {
            if (conn.State != System.Data.ConnectionState.Open)
            {
                conn.Open();
            }
        }

        public static void Close(SqlConnection conn)
        {
            if (conn.State != System.Data.ConnectionState.Closed)
            {
                conn.Close();
            }
        }

        public static void SaveSensorData(string tableName, float[] data, string date, string time, string henhouseName)
        {
            using (SqlConnection conn = CreateConnection())
            {
                Open(conn);
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = $"INSERT INTO {tableName} (Date, Temp, Humidity, PM25, NH3, CO2, Time, HenhouseName) VALUES ('{date}', {data[0]}, {data[1]}, {data[2]}, {data[3]}, {data[4]}, '{time}', '{henhouseName}')";
                cmd.ExecuteNonQuery();
                Close(conn);
            }
        }

    }

    public class User
    {
        public string Name { get; set; }
    }
}
